#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import logging
import os
from pathlib import Path
import time
from ark_trade.ark_email import ark_email_spider
from ark_webholding.ark_holding import ark_webholding_spider
from ark_run_sql.run_sql import run_sql
from ark_fundflow.ark_fundflow import ark_fundflow_spider

import smtplib
from email.mime.text import MIMEText

def log_process(log_path,log_rank):
    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG)  # or whatever
    handler = logging.FileHandler(log_path, 'w', 'utf-8')  # or whatever
    handler.setFormatter(
        logging.Formatter('%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'))  # or whatever
    logger.addHandler(handler)
    return logger

def send_email(subject,email_content_list):
    # 发送邮件相关参数
    smtpserver = 'smtp.mxhichina.com'  # 发件服务器
    port = 25  # 端口
    sender = 'zoey.yang@tradego8.com'  # 发件人邮箱
    psw = 'a123456.'  # 发件人密码
    # receiver = "zoey.yang@tradego8.com"       # 单个接收人
    receiver = ["zoey.yang@tradego8.com", "tradego_ark@163.com"]

    # 编辑邮件内容
    email_content_list=['<p>'+line+'</p>' for line in email_content_list]
    body = ''.join(email_content_list)  # 定义邮件正文为html
    msg = MIMEText(body, 'html', 'utf-8')
    msg['from'] = sender
    # msg['to'] = receiver
    msg['to'] = ";".join(receiver)
    msg['subject'] = subject

    # 发送邮件
    smtp = smtplib.SMTP()
    smtp.connect(smtpserver)    # 链接服务器
    smtp.login(sender, psw)     # 登录
    smtp.sendmail(sender, receiver, msg.as_string())  # 发送
    smtp.quit()             # 关闭

if __name__=='__main__':
    curr_path = os.getcwd() + '/'
    if not os.path.exists(curr_path + 'main_run_logs'): os.makedirs(curr_path + 'main_run_logs')
    start_date_str = str(time.strftime('%Y-%m-%d_%H', time.localtime()))
    log_path = curr_path + 'main_run_logs/' + Path(__file__).name.replace('.py', '') + '_%s.log' % start_date_str
    log_rank = logging.INFO
    logger=log_process(log_path,log_rank)

    #ark_trade
    email_spider = ark_email_spider(log_rank=log_rank)
    email_spider.run_add_all_email()
    logger.info('===ark_trade done===')

    #ark_holding
    holding_spider = ark_webholding_spider(is_crawl=True, log_rank=log_rank)
    holding_date_complete_flag,uncomplete_data_date=holding_spider.run()
    logger.info('===ark_holding done===')

    if holding_date_complete_flag:
        #run sql
        rs = run_sql(log_rank=log_rank)
        rs.execute_sql()
        logger.info('===run_sql done===')

        # ark_fundvaluecashintout
        fundflow_spider = ark_fundflow_spider(is_crawl=True, log_rank=log_rank)
        fundflow_spider.run()
        logger.info('===ark_fundvaluecashintout done===')
    else:
        logger.warning('===!!!本次ark_holding 数据不完整,不完整的数据为：%s',str(uncomplete_data_date))

    #发错误提醒邮件
    start_time_str = str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
    email_subject='ark_project_%s'%start_time_str
    email_content_list=[]
    log_content=open(log_path,'r',encoding='utf-8').readlines()
    for line in log_content:
        if '- ERROR:' in line:
            email_content_list.append(line)

    #有错误日志，则发邮件
    if email_content_list:
        send_email(email_subject,email_content_list)
        logger.info('===发送了日志错误邮件提醒===')
    else:
        logger.info('===没有发现有错误日志，不需要发送邮件===')
